import { makeAutoObservable, runInAction } from "mobx";
import { addApi, createCodeApi, selectByParentIdApi, selectOneApi, updateApi } from "./services";
import { message } from "antd";

export interface ColDataProps {
    id?: number;
    code?: string | number;
    name?: string | number;
    dataType?: string | number;
    dataTypeLength?: string | number;
    isKey?: string | number;
    isNull?: string | number;
    isInsert?: string | number;
    isEdit?: string | number;
    isList?: string | number;
    isQuery?: string | number;
    queryType?: string | number;
    isRequired?: string | number;
    htmlType?: string | number;
    parentId?: number;
    defaultValue?: string | number;
    featureName?: string;
    comboBox?: string;
}

export interface IndexInfoProps {
    id?: number;
    filedName?: any;
    comment?: string;
    indexType?: string;
}

class TableInfoStore {
    currentItem: any = {};
    tab = 'tab1';
    fieldInfoList: ColDataProps[] = [];
    indexInfoList: IndexInfoProps[] = [];
    editableKeys: React.Key[] = [];
    indexInfoKeys: React.Key[] = [];
    navigate: ((path: string) => void) | null = null;

    constructor() {

        makeAutoObservable(this);
    }

    private getPublicField(): ColDataProps[] {
        return [
            {
                id: Date.now() + 1,
                code: "id",
                name: "ID",
                dataType: "int",
                isKey: 1,
                isEdit: 1,
                isList: 1,
                isQuery: 1,
                queryType: "=",
            },
            {
                id: Date.now() + 2,
                code: "name",
                name: "名称",
                dataType: "varchar",
                dataTypeLength: 255,
                isInsert: 1,
                isEdit: 1,
                isList: 1,
                isQuery: 1,
                queryType: "LIKE",
            },
            {
                id: Date.now() + 3,
                code: "status",
                name: "状态",
                dataType: "tinyint",
                isEdit: 1,
                isList: 1,
                isQuery: 1,
                queryType: "=",
                defaultValue: 1
            },
            {
                id: Date.now() + 4,
                code: "created_at",
                name: "创建时间",
                dataType: "datetime",
                isList: 1,
                isQuery: 1,
                queryType: "BETWEEN",
            },
            {
                id: Date.now() + 5,
                code: "updated_at",
                name: "更新时间",
                dataType: "datetime",
                isList: 1,
            },
            {
                id: Date.now() + 6,
                code: "comment",
                name: "备注",
                dataType: "varchar",
                dataTypeLength: 255,
                isNull: 1,
                isInsert: 1,
                isEdit: 1,
                isList: 1,
                isQuery: 1,
                queryType: "LIKE",
            },
        ];
    }
    setNavigate=(navigate: ((path: string) => void) | null = null) =>{
        this.navigate = navigate;
    }
    addPage = () => {
        this.currentItem = {};
        this.indexInfoList=[];
        this.fieldInfoList = this.getPublicField();
    }

    selectOne = async (id: any) => {

        const hide = message.loading("正在获取详情");
        const res = await selectOneApi({
            id,
            queryChildren: true,
        });
        if (res.code === 200) {
            runInAction(() => {
                res.data.status = !!res.data.status;
                this.currentItem = res.data;

                this.fieldInfoList = res.data.fieldInfoList.length
                    ? res.data.fieldInfoList
                    : this.getPublicField();

                this.indexInfoList = res.data.indexInfoList.map((item: any) => ({
                    ...item,
                    filedName: item.filedName.split(",")
                }));
            });
        }
        hide();
        return res.data || {}
    }

    selectByParentId = async (id: number) => {
        const hide = message.loading("正在获取详情");
        try {
            const res = await selectByParentIdApi(id);
            if (res.code === 200) {
                runInAction(() => {
                    this.fieldInfoList = res.data.length > 0
                        ? [...res.data]
                        : this.getPublicField();
                });
            }
        } finally {
            hide();
        }
    }

    onFinish = async (values: any) => {
        if (this.currentItem.id) {
            this.runUpdate(values)
        } else {
            this.runAdd(values)
        }
    }

    runAdd = async (values: any) => {
        const indexList = this.indexInfoList.map(item => ({
            ...item,
            filedName: item.filedName?.join(",")
        }));

        const submitData = {
            ...values,
            indexInfoList: indexList,
            fieldInfoList: this.fieldInfoList
        };

        const hide = message.loading("正在提交");
        try {
            const res = await addApi(submitData);
            if (res.code === 200) {
                message.success("添加成功");
                this.navigate!(`/tableInfo/detail/${res.data.id}`)
            }
        } finally {
            hide();
        }
    }
    runUpdate = async (values: any) => {
        const indexList = this.indexInfoList.map(item => ({
            ...item,
            filedName: item.filedName?.join(",")
        }));

        const submitData = {
            ...this.currentItem,
            ...values,
            indexInfoList: indexList,
            fieldInfoList: this.fieldInfoList
        };

        const hide = message.loading("正在更新");
        try {
            const res = await updateApi(submitData);
            if (res.code === 200) {
                message.success("更新成功");
                this.selectOne(this.currentItem.id);
            }
        } finally {
            hide();
        }
    }


    addRow = () => {
        const now = Date.now();
        runInAction(() => {
            this.fieldInfoList = [...this.fieldInfoList, { id: now }];
            this.editableKeys = [now];
        });
    }

    deleteItem = (index: number) => {
        runInAction(() => {
            const list = [...this.fieldInfoList];
            list.splice(index, 1);
            this.fieldInfoList = list;
        });
    }

    canEditFieldInfo = (id: number) => {
        runInAction(() => {
            const index = this.editableKeys.indexOf(id);
            if (index === -1) {
                this.editableKeys = [...this.editableKeys, id];
            } else {
                const l = [...this.editableKeys];
                l.splice(index, 1);
                this.editableKeys = l;
            }
        });
    }

    addIndexInfoRow = () => {
        const now = Date.now();
        runInAction(() => {
            this.indexInfoList = [...this.indexInfoList, { id: now }];
            this.indexInfoKeys = [now];
        });
    }

    deleteIndexInfoItem = (index: number) => {
        runInAction(() => {
            const list = [...this.indexInfoList];
            list.splice(index, 1);
            this.indexInfoList = list;
        });
    }

    canEditIndexInfo = (id: number) => {
        runInAction(() => {
            const index = this.indexInfoKeys.indexOf(id);
            if (index === -1) {
                this.indexInfoKeys = [...this.indexInfoKeys, id];
            } else {
                const l = [...this.indexInfoKeys];
                l.splice(index, 1);
                this.indexInfoKeys = l;
            }
        });
    }

    createCodeClick = async () => {
        const hide = message.loading('正在提交---');
        try {
            const res = await createCodeApi({ id: this.currentItem.id });
            if (res.code === 200) {
                message.success("生成成功");
            }
        } finally {
            hide();
        }
    }

    setTab = (tab: string) => {
        this.tab = tab;
    }

    setCurrentItem = (item: any) => {
        this.currentItem = item;
    }

    setFieldInfoList = (list: ColDataProps[]) => {
        this.fieldInfoList = list;
    }

    setEditableRowKeys = (keys: React.Key[]) => {
        this.editableKeys = keys;
    }

    setIndexInfoList = (list: IndexInfoProps[]) => {
        this.indexInfoList = list;
    }

    setIndexInfoKeys = (keys: React.Key[]) => {
        this.indexInfoKeys = keys;
    }
}

export default new TableInfoStore();